package com.community.filter;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class HeaderInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ValueOperations<String, Object> redis = redisTemplate.opsForValue();
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        // 从请求头中获取Token
        String token = request.getHeader("token");
        String ownerPhone=request.getHeader("ownerPhoneNumber");
        String o = (String) redis.get(ownerPhone);
        System.out.println(token);
        System.out.println(ownerPhone);
        if(o==null){
            response.getWriter().write("登录失效");
            return false;
        }
       if(!o.equals(token)){
           response.getWriter().write("账号未登录");
            return false;
        }
        // 在这里可以添加更多的Token验证逻辑，例如查询Token的有效性等
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入拦截器=======执行中========");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入拦截器=======执行后========");
    }
}
